package com.dianban.controller;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.ShopUser;
import com.dianban.entity.User;
import com.dianban.plugin.weixinpay.LeshuaPayFacePlugin;
import com.dianban.plugin.weixinpay.WeixinPayFacePlugin;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.FacePayStoreOrderService;
import com.dianban.service.UserService;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * @author wujh
 * @create 2020/1/10
 */
@Api(value = "ApiWeixinController", description = "微信控制器")
@RestController
@RequestMapping(value = "${interfacePath}/weixin/")
public class ApiWeixinController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiWeixinController.class);

    @Autowired
    private WeixinPayFacePlugin weixinPayFacePlugin;
    @Autowired
    private LeshuaPayFacePlugin leshuaPayFacePlugin;
    @Autowired
    private UserService userService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayConfigService facePayConfigService;

    @ApiOperation(notes = "getWxpayfaceCodeParams", httpMethod = "POST", value = "进行人脸识别参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "商户用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "rawdata", value = "初始化数据", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "getWxpayfaceCodeParams", method = RequestMethod.POST)
    public ResultVo get_wxpayface_authinfo(String rawdata, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(rawdata)) {
            return ResultVo.error(ResultCode.ERROR, "初始化数据不能为空");
        }
        ShopUser shopUser = UserUtils.getShopUser(request);
        String screenMac = UserUtils.getScreenMac(request);
        String store_id = shopUser.getStoreId().toString();
        String device_id = shopUser.getStoreId().toString();
        String store_name = StringUtils.isBlank(shopUser.getNickname()) ? "门店名称" : shopUser.getNickname();
        List<FacePayConfig> facePayConfigList = facePayConfigService.find(30, 1, null);
        if (facePayConfigList != null && !facePayConfigList.isEmpty() && "1".equals(facePayConfigList.get(0).getValue())) {
            //ResultVo resultvo = leshuaPayFacePlugin.getWxpayfaceAuthinfo( store_id, store_name, device_id, rawdata,screenMac);
            ResultVo resultvo = weixinPayFacePlugin.getWxpayfaceAuthinfo(store_id, store_name, device_id, rawdata, screenMac);
            if (!"200".equals(resultvo.getCode())) {
                return resultvo;
            }
            HashMap<String, Object> resultMape = (HashMap<String, Object>) resultvo.getContent();
            String authinfo = (String) resultMape.get("authinfo");
            HashMap<String, Object> params = leshuaPayFacePlugin.getWxpayfaceCodeParams(store_id, authinfo);
            return ResultVo.success(params, "操作成功");
        } else {
            ResultVo resultvo = weixinPayFacePlugin.getWxpayfaceAuthinfo(store_id, store_name, device_id, rawdata, screenMac);
            if (!"200".equals(resultvo.getCode())) {
                return resultvo;
            }
            HashMap<String, Object> resultMape = (HashMap<String, Object>) resultvo.getContent();
            String authinfo = (String) resultMape.get("authinfo");
            HashMap<String, Object> params = weixinPayFacePlugin.getWxpayfaceCodeParams(store_id, authinfo);
            return ResultVo.success(params, "操作成功");
        }

    }

    @ApiOperation(notes = "micropay", httpMethod = "POST", value = "进行发起订单支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "screenMac", value = "屏幕Mac", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "shopUserToken", value = "门店用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "out_trade_no", value = "订单号", required = false, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "total_fee", value = "订单总金额，单位为分，只能为整数", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "face_code", value = "人脸凭证", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "spbill_create_ip", value = "调用微信支付API的机器IP", required = true, paramType = "query", dataType = "string"),

    })
    @RequestMapping(value = "micropay", method = RequestMethod.POST)
    public ResultVo micropay(Long userId, String out_trade_no, String face_code, String spbill_create_ip, Integer total_fee, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(face_code)) {
            return ResultVo.error(ResultCode.ERROR, "人脸凭证不能为空");
        }
        if (StringUtils.isBlank(spbill_create_ip)) {
            return ResultVo.error(ResultCode.ERROR, "机器IP不能为空");
        }
        if (userId == null) {
            return ResultVo.error(ResultCode.ERROR, "用户id不能为空");
        }
        User user = userService.findById(userId);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "用户id错误");
        }
        if (total_fee == null) {
            return ResultVo.error(ResultCode.ERROR, "订单总金额不能为空");
        }
        ShopUser shopUser = UserUtils.getShopUser(request);
        Long shopUserId = shopUser.getId();
        Long storeId = shopUser.getStoreId();
        String store_name = StringUtils.isBlank(shopUser.getNickname()) ? "门店名称" : shopUser.getNickname();
        String body = store_name;
        if (StringUtils.isBlank(out_trade_no)) {
            return ResultVo.error(ResultCode.ERROR, "订单号不能为空");
        }
        FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(out_trade_no);
        if (facePayStoreOrder == null) {
            return ResultVo.error(ResultCode.ERROR, "订单号错误");
        }
        BigDecimal money = facePayStoreOrder.getMoney();
        total_fee = money.multiply(new BigDecimal(100)).intValue();
        if (total_fee == 0) {
            return ResultVo.error(ResultCode.ERROR, "订单支付金额错误");
        }
        List<FacePayConfig> facePayConfigList = facePayConfigService.find(30, 1, null);
        ResultVo resultVo = null;
        if (facePayConfigList != null && !facePayConfigList.isEmpty() && "1".equals(facePayConfigList.get(0).getValue())) {
            try {
                facePayStoreOrderService.updatePayTypeAndChannel(facePayStoreOrder.getId(), "乐刷-青蛙设备-支付");
                resultVo = leshuaPayFacePlugin.micropay(storeId.toString(), body, out_trade_no, total_fee, spbill_create_ip, face_code);
                if (resultVo.getCode().equals(ResultCode.SUCESS.getCode())) {
                    facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
                }
            } catch (Throwable e) {
                logger.error("设备当前支付是乐刷刷脸支付，如果支付不了，则调用微信刷脸支付重新尝试一次");
                // TODO:这边做下特殊处理，如果乐刷付不了，那么还是调用下微信进行支付，解决小额度的支付
                facePayStoreOrderService.updatePayTypeAndChannel(facePayStoreOrder.getId(), "微信-青蛙设备-支付(乐刷异常处理)");
                resultVo = weixinPayFacePlugin.micropay(storeId.toString(), body, out_trade_no, total_fee, spbill_create_ip, face_code);
                if (resultVo.getCode().equals(ResultCode.SUCESS.getCode())) {
                    facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
                }
            }
        } else {
            try {
                facePayStoreOrderService.updatePayTypeAndChannel(facePayStoreOrder.getId(), "微信-青蛙设备-支付");
            } catch (Throwable e) {
            }
            resultVo = weixinPayFacePlugin.micropay(storeId.toString(), body, out_trade_no, total_fee, spbill_create_ip, face_code);
            if (resultVo.getCode().equals(ResultCode.SUCESS.getCode())) {
                facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
            }
        }

        return resultVo;
    }

    @RequestMapping(value = "leshua/asyncNotify/{sn}")
    public String asyncNotify(@PathVariable String sn, HttpServletRequest request) {
        String result = "";
        try {
            if (StringUtils.isBlank(sn)) {
                return result;
            }
            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(sn);
            if (facePayStoreOrder == null) {
                return result;
            }
            if (20 == facePayStoreOrder.getPayStatus()) {
                return leshuaPayFacePlugin.getNotifyMessage();
            }
            String tradeSn = leshuaPayFacePlugin.verifyNotify(sn, facePayStoreOrder.getMoney(), request);
            if (StringUtils.isNotBlank(tradeSn)) {
                int count = facePayStoreOrderService.updateStateAndCommission(facePayStoreOrder);
                if (count == 1) {
                    return leshuaPayFacePlugin.getNotifyMessage();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

}
